<?php
namespace app\modules\merchant\forms;

use app\common\forms\BaseForm;
use app\config\Constants;
use app\models\Merchant;
use app\models\MerchantCredential;
use app\modules\merchant\services\UserService;

/**
 * LoginForm is the model behind the login form.
 *
 * @property Merchant|null $user This property is read-only.
 *
 */
class LoginForm extends BaseForm
{
    public $username;
    public $password;

    /**
     * @var MerchantCredential
     */
    private $_user = false;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required','message'=>\Yii::t("app","用户名或密码不能为空")],
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if ($this->hasErrors()) {
            return;
        }

        $user = $this->getUser();
        if (!$user) {
            $this->addError("username",\Yii::t("app","用户名或密码错误"));
            return;
        }
        if(!\Yii::$app->getSecurity()->validatePassword($this->$attribute,$user->content)){
            $this->addError("password",\Yii::t("app","用户名或密码错误"));
            return;
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            $merchant = $this->getUser()->merchant;
            return \Yii::$app->getModule("merchant")->user->login($merchant);
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return MerchantCredential|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = UserService::findInfoByCredential($this->username,Constants::USERNAME);
        }

        return $this->_user;
    }
}